<?php
require_once "includes/config.php";
require_once "includes/functions.php";
require_once 'includes/class.phpmailer.php';
require_once('AmazonAPI/.config.inc.php');
ob_start();
session_start();
$sessid=session_id();
$msg = "";

$service = new AmazonAPI_FPS_Client(AWS_ACCESS_KEY_ID, 
                                       AWS_SECRET_ACCESS_KEY);
$request =  new AmazonAPI_FPS_Model_PayRequest();


if(isset($_REQUEST['signature']) && !empty($_REQUEST['signature'])) {
	$tokenID = $_REQUEST['tokenID'];
	$callerReference = $_REQUEST['callerReference'];
	//print_r($_SESSION); exit;
									   
	$total_recipients = count($_SESSION['recipient_tokens']);
	$loop_limit = ($total_recipients - 1);
	for($i=0;$i<=$loop_limit;$i++){
		
		//echo $_SESSION['recipient_tokens'][$i]."<br />"; exit;
		$request->setCallerDescription('Swapen');
		$request->setCallerReference("swapen".rand());
		
		$request->setMarketplaceVariableFee('3.1');
		$request->setRecipientTokenId($_SESSION['recipient_tokens'][$i]);
		
		$request->setSenderTokenId($tokenID);//set the proper senderToken here.
		
		$amount = new AmazonAPI_FPS_Model_Amount();
		$amount->setCurrencyCode("USD");
		$amount->setValue($_SESSION['recipient_amounts'][$i]); //set the transaction amount here;
		
		$request->setTransactionAmount($amount);
	
	 // object or array of parameters
	  	$return = invokePay($service, $request);
		//$return=true;
		
		//$sqlSelItem_comm="SELECT b.* FROM tbl_bargain b LEFT JOIN tbl_items i ON b.item_id = i.product_id WHERE i.item_id =".$_SESSION['item_arr'][$i]." and bargain_status='1' order by bargain_id desc";
		$sqlSelItem_comm="SELECT * FROM tbl_items where item_id=".$_SESSION['item_arr'][$i]." ";
		$rstSelItem_comm=mysql_query($sqlSelItem_comm);
		$rowSelItem_comm=mysql_fetch_array($rstSelItem_comm);
		
		$sqlSelItem_comm1="SELECT * FROM tbl_product where product_id=".$rowSelItem_comm['product_id']." ";
		$rstSelItem_comm1=mysql_query($sqlSelItem_comm1);
		$rowSelItem_comm1=mysql_fetch_array($rstSelItem_comm1);
		
		if($rowSelItem_comm['quantity']>0);
		$sql=mysql_query("update tbl_items set quantity=quantity-1 where item_id='".$_SESSION['item_arr'][$i]."'") or mysql_error();
		
		if($rowSelItem_comm1['quantity']>0)
		$sql=mysql_query("update tbl_product set quantity=quantity-1 where product_id='".$rowSelItem_comm['product_id']."'") or mysql_error();
		
		//exit();
		if(is_array($rowSelItem_comm))
		{
			if($rowSelItem_comm['owner_id']=='0')
			{
				$product_id=$rowSelItem_comm['product_id'];	
				$to_user_id=$rowSelItem_comm['seller_id'];	
				$comm_amt=$rowSelItem_comm['commission'];
				$is_comm_paid=0;
				
				$sqlSelItem_comm1="SELECT * FROM tbl_bargain where item_id=".$product_id." and user_type=3 and bargain_status=1 and bargain_type=1 order by bargain_id desc limit 0,1";
				$rstSelItem_comm1=mysql_query($sqlSelItem_comm1);
				$rowSelItem_comm1=mysql_fetch_array($rstSelItem_comm1);
				if(is_array($rowSelItem_comm1))
				{
					$by_user_id=$rowSelItem_comm1['user_id'];
				}
			}
			else
			{
				$product_id=$rowSelItem_comm['product_id'];	
				$to_user_id=$rowSelItem_comm['seller_id'];
				
				$by_user_id=$rowSelItem_comm['owner_id'];
				$is_comm_paid=0;
				$comm_amt=$rowSelItem_comm['commission'];
			}
			//exit();
		}
		else
		{
			$by_user_id=0;
			$to_user_id=0;
			$comm_amt=0;
			$is_comm_paid=0;
		}	
				
		$sqlTemp_comm="SELECT * FROM tempcart where tempid='".$_SESSION['tempID_arr'][$i]."' ";
		$rstTemp_comm=mysql_query($sqlTemp_comm);
		$rowTemp_comm=mysql_fetch_array($rstTemp_comm);
		if(is_array($rowTemp_comm) && $return[2]!="Failure")
		{
			if((int)$rowTemp_comm['is_online']==0)
			{
				$verify_code=$rowTemp_comm['verify_code'];				
					
					$msg="<table width='100%' border='0' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:12px; line-height:25px'>
					  <tr>
						<td width='18%' height='41'><table width='100%' border='0'>
						  <tr>
							<td width='19%' height='68'><img src='http://genisofttechnologies.com/php1/swapen/images/logo.gif' width='208' height='83'></td>
							<td width='81%'>Swapen sent this message from Product sold for Local Pickup.</td>
						  </tr>
						</table></td>
					  </tr>
					  <tr>
						<td height='32' colspan='2' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:13px;color:#FFFFFF;background-color:#0FB6FA;'><b>&nbsp;&nbsp;Congrats! You have brought '".$rowSelItem_comm['product_description']."'</b></td>
					  </tr>
					  <tr>
						<td>
						  <table width='100%' border='0'>
							<tr>
							  <td width='71%' height='124'><p><b>Hi </b>, </p>
							  <p>Your product verification code is: ".$verify_code."</p></td>
							  <td width='29%' style='text-align:center'></td>
							</tr>
						  </table>
						</td>
					  </tr>
					  <tr>
						<td><table width='100%' border='0'>
						  <tr>
							<td height='28' style='background-color:#F3F3F3'><b>If the above link does not work:</b></td>
						  </tr>
						  <tr>
							<td height='80'>Type in or copy and paste this link into your Web browser: <br>
							  <a href='swapen.com/index.php' target='_blank'>http://swapen.com/index.php </a><br></td>
						  </tr>
						</table></td>
					  </tr>
					</table>
					";					
					$to = $_SESSION['user_email'];				
					$subject = ": Your purchased product code within Swapen.com";
					$body=$msg;				
					$from="mail@swapen.com";
					$header = 'From:'.$from.' \r\n';
					$header.='MIME-Version: 1.0' . "\r\n";
					$header.='Content-type: text/html; charset=iso-8859-1' . "\r\n";
					$header.='X-Mailer: PHP/' . phpversion();							
					mail($to,$subject,$body,$header);
					//$mail = new PHPMailer(); // defaults to using php "mail()"
//					$mail->MsgHTML($msg);
//					$mail->From       = "mail@swapen.com";
//					$mail->FromName   = "Swapen.com";
//					$mail->Subject    =": Your purchased product code within Swapen.com";
//					$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
//					$mail->AddAddress($_SESSION['user_email'], $_SESSION['user_email']);
//					$mail->Send();
			}	
			else
			{
				$verify_code='';
			}			
		}
					
		//print_r($return);
		$log = serialize($return);
		file_put_contents('log.txt',$log);
		if($return  && $return[2]!="Failure"){
			$q = "INSERT INTO tbl_orders SET
					transaction_ID = '".$return[1]."',
					item_code = '".$_SESSION['item_code'][$i]."',
					order_amount = '".$_SESSION['recipient_amounts'][$i]."',
					transaction_status = '".$return[2]."',
					requestId = '".$return[3]."', 
					item_id = '".$_SESSION['item_arr'][$i]."',
					item_name = '".$_SESSION['itemname_arr'][$i]."',
					qty = '".$_SESSION['qty_arr'][$i]."',
					sales_tax='".$_SESSION['sales_tax_arr'][$i]."',
					ordered_by = '".$_SESSION['user_id_sess']."',
					order_comm = '".$comm_amt."',
					order_comm_to_user_id = '".$to_user_id."',
					order_comm_by_user_id = '".$by_user_id."',
					is_comm_paid = '".$is_comm_paid."',
					verify_code='".$verify_code."',
					is_online='".$rowTemp_comm['is_online']."',
					order_date = '".date('Y-m-d')."'";
			mysql_query($q);
			//delete cart
			//echo $q;
			//exit();
			
			$qd = "DELETE FROM tempcart WHERE tempid = '".$_SESSION['tempID_arr'][$i]."' WHERE tempid NOT IN (select tempid from tempcart where draftpost > '".date("Y-m-d G:i:s",time())."')";
			mysql_query($qd);
			
			$sqlSelItem="select * from tbl_referer where refer_to_user_id =".$_SESSION['user_id_sess']." and isActive='1'";
			$rstSelItem=mysql_query($sqlSelItem);
			$rowSelItem=mysql_fetch_array($rstSelItem);
			
			if(is_array($rowSelItem))
			{
				$comm=number_format((0.5*($_SESSION['recipient_amounts'][$i])/100),2);
				$sqlPost="insert tbl_refer_comm(refer_by_user_id,refer_to_user_id,item_id,transaction_id,refer_comm,buy_date,item_code)
				 values('".$rowSelItem['refer_by_user_id']."','".$_SESSION['user_id_sess']."','".$_SESSION['item_arr'][$i]."','".$return[1]."','".$comm."',Now(),'".$_SESSION['item_code'][$i]."')";
				//$sqlPost="update tbl_referer set refer_to_user_id='".$insertedId."',isActive='1' where ref_email like '%".$email."%'";
				//echo $sqlPost;
				//exit();
				$rstPost=mysql_query($sqlPost) or die(mysql_error());
				
				$sqlPost1="update tbl_items_code set isSold='1',buy_by='".$_SESSION['user_id_sess']."' where code='".$_SESSION['item_code'][$i]."' ";
				$rstPost1=mysql_query($sqlPost1) or die(mysql_error());	
				
				
				//print_r($rowSelItem);
				//exit();	
			}
			else
			{
					$sqlSelItem="select * from tbl_items where item_id ='".$_SESSION['item_arr'][$i]."'";
					$rstSelItem=mysql_query($sqlSelItem);
					$rowSelItem=mysql_fetch_array($rstSelItem);	
					if(is_array($rowSelItem))
					{
						$seller_id=$rowSelItem['seller_id'];
						$owner_id=$rowSelItem['owner_id'];
						
						$sqlSelItem1="select * from tbl_referer where refer_to_user_id ='".$seller_id."' and isActive='1'";
						$rstSelItem1=mysql_query($sqlSelItem1);
						$rowSelItem1=mysql_fetch_array($rstSelItem1);	
						if(is_array($rowSelItem1))
						{
							$user_comm_id=$rowSelItem1['refer_by_user_id'];	
							if((int)$user_comm_id==(int)$_SESSION['user_id_sess'])
							{
								$comm=number_format((0.5*($_SESSION['recipient_amounts'][$i])/100),2);
								$sqlPost="insert tbl_refer_comm(refer_by_user_id,refer_to_user_id,item_id,transaction_id,refer_comm,buy_date,item_code)
								 values('".$user_comm_id."','".$seller_id."','".$_SESSION['item_arr'][$i]."','".$return[1]."','".$comm."',Now(),'".$_SESSION['item_code'][$i]."')";
								$rstPost=mysql_query($sqlPost) or die(mysql_error());	
															
								$user_comm_id=0;
							}										
						}
						else
						{
						
							$sqlSelItem2="select * from tbl_referer where refer_to_user_id ='".$owner_id."' and isActive='1'";
							$rstSelItem2=mysql_query($sqlSelItem2);
							$rowSelItem2=mysql_fetch_array($rstSelItem2);
							if(is_array($rowSelItem2))
							{
								$user_comm_id=$rowSelItem2['refer_by_user_id'];	
								if((int)$user_comm_id==(int)$_SESSION['user_id_sess'])
								{
									$comm=number_format((0.5*($_SESSION['recipient_amounts'][$i])/100),2);
									$sqlPost="insert tbl_refer_comm(refer_by_user_id,refer_to_user_id,item_id,transaction_id,refer_comm,buy_date,item_code)
									 values('".$user_comm_id."','".$owner_id."','".$_SESSION['item_arr'][$i]."','".$return[1]."','".$comm."',Now(),'".$_SESSION['item_code'][$i]."')";
									$rstPost=mysql_query($sqlPost) or die(mysql_error());	
								
									$user_comm_id=0;
								}				
							}
							else
							{
								$user_comm_id=0;
							}
							//$user_comm_id=$owner_id;
						}					
						if((int)$user_comm_id!=0)
						{
							$comm=number_format((0.5*($_SESSION['recipient_amounts'][$i])/100),2);
							$sqlPost="insert tbl_refer_comm(refer_by_user_id,refer_to_user_id,item_id,transaction_id,refer_comm,buy_date,item_code)
							 values('".$user_comm_id."','".$_SESSION['user_id_sess']."','".$_SESSION['item_arr'][$i]."','".$return[1]."','".$comm."',Now(),'".$_SESSION['item_code'][$i]."')";
							$rstPost=mysql_query($sqlPost) or die(mysql_error());
							
							$sqlPost1="update tbl_items_code set isSold='1' where code='".$_SESSION['item_code'][$i]."' ";
							$rstPost1=mysql_query($sqlPost1) or die(mysql_error());	
						}
						else
						{
							$sqlPost1="update tbl_items_code set isSold='1' where code='".$_SESSION['item_code'][$i]."' ";
							$rstPost1=mysql_query($sqlPost1) or die(mysql_error());	
						}
						//echo $sqlPost;
						//exit();		
					}
					//else
//					{
//						$sqlSelItem1="select * from tbl_items where item_id ='".$_SESSION['item_arr'][$i]."'";
//						$rstSelItem1=mysql_query($sqlSelItem1);
//						$rowSelItem1=mysql_fetch_array($rstSelItem1);	
//						
//						if(is_array($rowSelItem1))
//						{
//							$owner_id=$rowSelItem1['owner_id'];
//							
//							$comm=number_format((0.5*($_SESSION['recipient_amounts'][$i])/100),2);
//							$sqlPost="insert tbl_refer_comm(refer_by_user_id,refer_to_user_id,item_id,transaction_id,refer_comm,buy_date,item_code)
//							 values('".$owner_id."','".$_SESSION['user_id_sess']."','".$_SESSION['item_arr'][$i]."','".$return[1]."','".$comm."',Now(),'".$_SESSION['item_code'][$i]."')";
//							$rstPost=mysql_query($sqlPost) or die(mysql_error());	
//							
//							$sqlPost1="update tbl_items_code set isPaid='1' where code='".$_SESSION['item_code'][$i]."' ";
//							$rstPost1=mysql_query($sqlPost1) or die(mysql_error());	
//														
//						}
//					}				
						
			}			
			$_SESSION['order_msg'] = "Your transaction is successfull";
			header("location:index.php?order");
		}
		else
		{
			header("location:index.php?cart");
		}
	}
	//get users order status
	/*$oq = "SELECT * FROM tbl_orders WHERE ordered_by = '".$_SESSION['user_id_sess']."' AND order_date = '".date('Y-m-d')."'";
	$or = mysql_query($oq) or die(mysql_error($oq));
	$oc = mysql_num_rows($or);
	if($oc == 0){
		$_SESSION['cart_msg'] = "Your transaction is not successfull";
		header("location:index.php?cart");
	}else{
		if(empty($msg)){
			$_SESSION['order_msg'] = "Your transaction is successfull";		
		}else{
			$_SESSION['order_msg'] = $msg;
		}
		header("location:index.php?order");
	}*/
	
	//use the above token ID to pay
}
function invokePay(AmazonAPI_FPS_Interface $service, $request) 
  {
      try {
              $response = $service->pay($request);
			  //$res_arr = array();
			  if($response){
			  	$payResult = $response->getPayResult();
				//$PayResult = $response->getPayResult();
				$TransactionId = $payResult->getTransactionId();
				$TransactionStatus = $payResult->getTransactionStatus();
				$responseMetadata = $response->getResponseMetadata();
				$RequestId = $responseMetadata->getRequestId();
			  	$res_arr = array($PayResult,
								 $TransactionId,
								 $TransactionStatus,
								 $RequestId
				);
			  }
			  return $res_arr;
              
                

     } catch (AmazonAPI_FPS_Exception $ex) {
         echo("Caught Exception: " . $ex->getMessage() . "\n");
         echo("Response Status Code: " . $ex->getStatusCode() . "\n");
         echo("Error Code: " . $ex->getErrorCode() . "\n");
         echo("Error Type: " . $ex->getErrorType() . "\n");
         echo("Request ID: " . $ex->getRequestId() . "\n");
         echo("XML: " . $ex->getXML() . "\n");
		 return false;
     }
 }
?>